/*
用于将form表单的控件对象序列化为对象，方便列表查询时不用手动拼接条件
调用例子：$("#form1").serializeObject();
*/
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

// select 控件绑定数据
/*
*data:数据源
*id：目标元素
*selectValue:默认选中的option的Value
*/
var appendOption = function (data, id, selectValue) {
    $.each(data, function (i, item) {
        if (selectValue && item.Id == selectValue) {
            $('<option selected></option>').val(item.Id).text(item.Name).appendTo($(id));
        }
        else {
            $('<option></option>').val(item.Id).text(item.Name).appendTo($(id));
        }
    });
};


//bootstrap-table 显示行号
var RowNumber = function (value, row, index) {
    return index + 1;
};

//bootstrap-table 日期格式化
var yyyy_mm_dd = function (value, row, index) {

    var reg = /\/Date\(([-]?\d+)\)\//gi;

    if (reg.test(value)) {
        var msec = value.toString().replace(reg, "$1");
        value = new Date(parseInt(msec)).Format('yyyy-MM-dd');
    }
    return value;
};

//bootstrap-table 日期格式化
var hh_mm_ss = function (value, row, index) {
    var reg = /\/Date\(([-]?\d+)\)\//gi;

    if (reg.test(value)) {
        var msec = value.toString().replace(reg, "$1");
        value = new Date(parseInt(msec)).Format('hh:mm:ss');
    }
    return value;
};

//bootstrap-table 显示数据截断
var cutOff = function (value, row, index) {
    var str = value;

    if (value.length > 10) {
        str = value.substr(0, 10) + '...';
    }
    return str;
};

//限制只能输入 数字
var inputInt = function (obj) {//限制只能输入Int
    obj.value = obj.value.replace(/[^\d]/g, '');

    //obj.val(obj.val().replace(/[^\d]/g, ''));
};

//限制只能输入 数字，可带小数
var inputFloat = function (obj) {//可输入Float，保留一位小数
    obj.value = obj.value.replace(/[^\d.]/g, "");  //清除“数字”和"."以外的字符
    obj.value = obj.value.replace(/^\./g, "");  //验证第一个字符是数字而不是"."
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个"."清除多余的"."
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");

    if (obj.value.indexOf(".") == -1) return;

    var strValue = obj.value;//保留1位小数点
    var length = strValue.substring(obj.value.indexOf("."), obj.value.length).length;
    if (length > 3) obj.value = obj.value.substring(-1, obj.value.indexOf(".") + 3);
};

//bootstrap toast 浮动提示
var i = -1,
    toastCount = 0,
    $toastlast,
    getMessage = function () {
        var msgs = ['Hello, some notification sample goes here',
            'Did you like this one ? :)',
            'Totally Awesome!!!',
            'Yeah, this is the Metronic!',
            'Explore the power of App. '
            //'Explore the power of App. '
        ];
        i++;
        if (i === msgs.length) {
            i = 0;
        }

        return msgs[i];
    };

//显示浮动提示框
var showToast = function (type, title, message) {

    var toastType = ['success', 'info', 'warning', 'error'];
    //toastr[success]("Gnome & Growl type non-blocking notifications", "Toastr Notifications");
    if (type > 3) type = 1;
    if (!message) message = getMessage();

    toastr[toastType[type]](message, title);

    //toastr.options = {
    //    closeButton: true,
    //    debug: true,
    //    positionClass: 'toast-top-right',
    //    onclick: null
    //};

    //toastr.options = {
    //    "closeButton": true,
    //    "debug": false,
    //    "positionClass": "toast-top-right",
    //    "onclick": null,
    //    "showDuration": "1000",
    //    "hideDuration": "1000",
    //    "timeOut": "5000",
    //    "extendedTimeOut": "1000",
    //    "showEasing": "swing",
    //    "hideEasing": "linear",
    //    "showMethod": "fadeIn",
    //    "hideMethod": "fadeOut"
    //};
};


var postQueryParams = function (params) {

    //console.log(JSON.stringify(params));
    // {"limit":10,"offset":0,"order":"asc","your_param1":1,"your_param2":2}
    return params; // body data
};

var getT2mCookie = function(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}, setT2mCookie = function(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
    ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())+";path="+escape("/T2Mobile/");
};
//写cookies 

function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}

//读取cookies 
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}

//删除cookies 
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/";
}

/**
 * 表单验证
 * JQ_Form form的JQ对象
 * rules 验证规则对象
 * submitHandlerFunction(form) 验证成功回调函数
 */
var customFormValidate = function(JQ_Form, rules,submitHandlerFunction,messages){
	var error1 = $('.alert-error', JQ_Form);
    var success1 = $('.alert-success', JQ_Form);
    rules = rules || {};
    messages= messages||{};
    JQ_Form.validate({
        errorElement: 'span', //default input error message container
        errorClass: 'help-block help-block-error', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        ignore: "",
        rules: rules,
        invalidHandler: function (event, validator) { //display error alert on form submit
            success1.hide();
            error1.show();
            //App.scrollTo(error1, -200);
        },

        errorPlacement: function (error, element) { // render error placement for each input type
            var icon = $(element).parent('.input-icon').children('i');
            icon.removeClass('fa-check').addClass("fa-warning");
            icon.attr("data-original-title", error.text()).tooltip({ 'container': 'body' });
        },

        highlight: function (element) { // hightlight error inputs
            $(element).closest('.form-group').removeClass("has-success").addClass('has-error'); // set error class to the control group
        },

        unhighlight: function (element) { // revert the change done by hightlight

        },
        messages:messages,
        	
        success: function (label, element) {
            var icon = $(element).parent('.input-icon').children('i');
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
            icon.removeClass("fa-warning").addClass("fa-check");
        },
        submitHandler: function (form) {
            success1.show();
            error1.hide();
            if(typeof submitHandlerFunction == 'function'){
            	submitHandlerFunction(form);
            }
        }
    });
};
/**
 * 获取Office文件图标 图片路径
 * suffixOrFilePath string 目标文件后缀名或者路径
 * size  int 文件尺寸(支持16 24 32 48 72 96 128)
 */
var getOfficeIconsPath = function (suffixOrFilePath, size) {
    var suffix = "pdf";
    if (suffixOrFilePath) {
        suffix = suffixOrFilePath.toLocaleLowerCase();
        if (suffixOrFilePath.lastIndexOf(".") != -1) {
            suffix = suffixOrFilePath.substr(suffixOrFilePath.lastIndexOf(".") + 1).toLocaleLowerCase();
        }
    }
    
    switch (suffix) {
        case "doc":
        case "docx":
            return "/images/file_icons/docx/Word_" + size + "x" + size + ".png";
        case "xls":
        case "xlsx":
            return "/images/file_icons/xlsx/Excel_" + size + "x" + size + ".png";
        case "ppt":
        case "pptx":
            return "/images/file_icons/pptx/PowerPoint_" + size + "x" + size + ".png";
        default:
            return "/images/file_icons/pdf/pdf_"+size+"x"+size+".png";

    }
};

var getUrlParam = function (name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
/**
    * 下拉选择框数据绑定
    * ajaxUrl GET方式的 数据接口地址
    * selectId 要绑定的下拉选择框控件ID
    * textValueInputId 要保存 textValue值的input控件的ID[可选参数，可以为空，为空时没有意义]
    * selectedId 初始加载数据选中项 selectValue值[可选参数]
    * callBackFunction 自定义回调函数callBackFunction(selectedValue, selectedText)[可选]  
    */
,loadDataToSelect = function (ajaxUrl, selectId, textValueInputId, selectedId, callBackFunction) {
    $.getJSON(ajaxUrl, function (data) {
        if (data.Success) {
            $.each(data.Value, function (i, item) {
                var selected = "";
                if (item.Id === selectedId) {
                    selected = "selected=\"selected\"";
                    $("#" + textValueInputId).val(item.Value);
                }
                $("#" + selectId).append("<option value=\"" + item.Id + "\" " + selected + ">" + item.Value + "</option>");
            });
            //如果给了 textValueInputId 就需要注册 onChange事件
            if (textValueInputId) {
                $("#" + selectId).change(function() {
                    var text = $("option:selected", $(this)).text();
                    if (text !== "请选择")
                        $("#" + textValueInputId).val(text);
                });
            }

            if (callBackFunction && typeof callBackFunction === "function") {
                var option = $("#" + selectId + " option:selected");
                var selectedValue = option.attr('value'),
                    selectedText =  option.text();
                callBackFunction(selectedValue, selectedText);
            }
        }
    });
};

(function ($) {
    //备份jquery的ajax方法
    var _ajax = $.ajax;

    //重写jquery的ajax方法
    $.ajax = function (opt) {
        //备份opt中error和success方法
        var fn = {
            error: function (XMLHttpRequest, textStatus, errorThrown) { },
            success: function (data, textStatus) { },
            complete: function (data, textStatus) { }
        }
        if (opt.error) {
            fn.error = opt.error;
        }
        if (opt.error) {
            fn.error = opt.error;
        }
        if (opt.success) {
            fn.success = opt.success;
        }

        if (opt.complete) {
            fn.complete = opt.complete;
        }

        //扩展增强处理
        var _opt = $.extend(opt, {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //错误方法增强处理
                fn.error(XMLHttpRequest, textStatus, errorThrown);
                if (errorThrown === "Unauthorized") {
                    location.href = "/login";
                }
            },
            success: function (data, textStatus) {
                //成功回调方法增强处理
                fn.success(data, textStatus);
            },
            beforeSend: function (request) {
                //提交前回调方法
                request.setRequestHeader("AreaId", $("#AreaId").val());
                //$('body').append("<div id='ajaxInfo' style=''>正在请求数据,请稍等...</div>");
            },
            complete: function (XHR, TS) {
                //请求完成后回调函数 (请求成功或失败之后均调用)。
                //$("#ajaxInfo").remove();;
                //解决bootstarptable的重写ajax的bug
                $('.fixed-table-loading').hide();
            }
        });
       return _ajax(_opt);
    };
})(jQuery);